package com.zmj.sy.mom.srv.aps.utils.schedulerole.impl;

import com.google.common.collect.Lists;
import com.zmj.sy.mom.srv.aps.bean.bo.ApsSchedulingOrderCache;
import com.zmj.sy.mom.srv.aps.bean.bo.CacheFactory;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsBatch;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsOrder;
import com.zmj.sy.mom.srv.aps.bean.entity.order.Order;
import com.zmj.sy.mom.srv.aps.bean.vo.apsorder.ApsOrderScheduleReqVo;
import com.zmj.sy.mom.srv.aps.mapper.ApsOrderMapper;
import com.zmj.sy.mom.srv.aps.mapper.OrderMapper;
import com.zmj.sy.mom.srv.aps.utils.schedulerole.ScheduleRole;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class SeqScheduleRole implements ScheduleRole {

    private final OrderMapper orderMapper;
    private final ApsOrderMapper apsOrderMapper;

    @Override
    public List<ApsOrder> sort(List<ApsOrder> apsOrders, ApsOrderScheduleReqVo reqVo) {

        // 移动的数据在seq字段中存着

        // 1.先根据order的顺序排序
        List<Order> orders = orderMapper.selectBatchIds(apsOrders.stream().map(ApsOrder::getOrderId).collect(Collectors.toList()));
        orders.sort(Comparator.comparing(Order::getSeq));

        List<ApsOrder> result = Lists.newArrayList();
        for (Order order : orders) {
            List<ApsOrder> currentOrder = apsOrders.stream().filter(apsOrder -> apsOrder.getOrderId().equals(order.getId())).sorted(Comparator.comparing(ApsOrder::getSeq)).collect(Collectors.toList());
            result.addAll(currentOrder);
        }
        // 移动的数据在seq字段中存着
        // 先排总订单，再排每个订单的包
        return result;
    }

    @Override
    public Integer getMyCode() {
        return SEQ;
    }

    @Override
    public List<ApsOrder> sort(CacheFactory reqVo, ApsBatch batch, List<Order> orders) {

        List<Integer> orderIdList = orders.stream().map(BaseEntity::getId).distinct().collect(Collectors.toList());

        List<ApsOrder> list = apsOrderMapper.lambdaQuery()
                .in(ApsOrder::getOrderId, orderIdList)
                .list();

        Map<Integer, Order> collect = orders.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        list.sort(
                Comparator.comparing((ApsOrder e) -> collect.get(e.getOrderId()).getSeq())
                        .thenComparing(ApsOrder::getSeq)
        );

        return list;
    }

}
